package com.asen.commons.core.jdbc.handler;

import java.math.BigDecimal;
import java.sql.*;
import java.util.Collection;

/**
 * BigDecimal类型处理器
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-02
 */
public class BigDecimalTypeHandler extends BaseTypeHandler<BigDecimal> {

    @Override
    public int getSqlType() {
        return Types.NUMERIC;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BigDecimal parameter)
            throws SQLException {
        ps.setBigDecimal(i, parameter);
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return rs.getBigDecimal(columnName);
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return rs.getBigDecimal(columnIndex);
    }

    @Override
    public BigDecimal getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return cs.getBigDecimal(columnIndex);
    }

    @Override
    public String toSqlValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof BigDecimal[]) {
            StringBuilder sb = new StringBuilder(0);
            sb.append("(");
            for (BigDecimal s : (BigDecimal[]) value) {
                if (s == null) {
                    continue;
                }
                if (sb.length() > 0) {
                    sb.append(", ");
                }
                sb.append(String.valueOf(s.toString()));
            }
            sb.append(")");
            return sb.toString();
        }

        if (value instanceof Collection) {
            return getSqlValue((Collection) value, false);
        }

        return String.valueOf(value);
    }

    @Override
    public BigDecimal getValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }

        return new BigDecimal(value.toString());
    }
}
